package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;


import cn.edu.dlut.ssdut.foodCredit2012.model.FinanceCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class FinanceCollectionService {
	
	public void add(FinanceCollection f)throws Exception {
		if(!hasFinance(f)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(f);
			session.getTransaction().commit();
		}
	}
	
	public void delete(FinanceCollection f) throws Exception{
		if(hasFinance(f)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(f);
			session.getTransaction().commit();
		}
	}
	
	public void update (FinanceCollection f) throws Exception{
		if(hasFinance(f)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(f);
			session.getTransaction().commit();
		}
	}
	
	/*public List financeList() {
		List financeList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Finance");
		query.setFirstResult(2);
		query.setMaxResults(10);
		financeList = query.list();
		
		session.getTransaction().commit();
		
		return financeList;
	}*/
	
	public boolean hasFinance(FinanceCollection f) throws Exception {
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from FinanceCollection f where f.licenceID = :licenceID")
			.setString("licenceID", f.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public FinanceCollection load(FinanceCollection f) throws Exception{
		if(hasFinance(f)){
			f = loadByLicenceID(f.getLicenceID());
			return f;
		}
		return f;
	}
	
	public FinanceCollection loadByLicenceID(String licenceID) throws Exception{
		FinanceCollection f = new FinanceCollection();
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		f = (FinanceCollection)session.createQuery("select f from FinanceCollection f where f.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		
		session.getTransaction().commit();
		return f;
	}

}
